﻿using System.Windows;
using System.Windows.Media;

namespace Red.Controls.TimeLine.Utils
{
    public static class VisualTreeUtils
    {
        public static T FindParent<T>( DependencyObject child ) where T : DependencyObject
        {
            DependencyObject parentObject = VisualTreeHelper.GetParent( child );
            if ( parentObject == null )
            {
                return default( T );
            }

            if ( parentObject is T )
            {
                return (T)parentObject;
            }

            return VisualTreeUtils.FindParent<T>( parentObject );
        }

        public static T GetChild<T>( this DependencyObject element ) where T : DependencyObject
        {
            if ( element == null )
            {
                return default( T );
            }

            int count = VisualTreeHelper.GetChildrenCount( element );
            for ( int i = 0; i < count; i++ )
            {
                DependencyObject child = VisualTreeHelper.GetChild( element, i );

                if ( child is T )
                {
                    return (T)child;
                }

                child = VisualTreeUtils.GetChild<T>( child );
                if ( child is T )
                {
                    return (T)child;
                }
            }

            return null;
        }
    }    
}
